//
//  MeViewController.m
//  wifi4.2
//
//  Created by 郭四虎 on 15/11/10.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "MeViewController.h"
#import "FunctionViewCell.h"
#import "MeDetailViewController.h"
#import "MyNumberViewController.h"
#import "RecommendViewController.h"
#import "SystemNotificationController.h"
#import "SuggestionViewController.h"
#import "SettingViewController.h"
#import "SystemNotiModel.h"
#import "VideoRecordController.h"
#import "ProductShowController.h"
#import "ForgetPasswordControllerViewController.h"
#import "BindNumViewController.h"
#import "MyWalletController.h"

@interface MeViewController ()
{
    UIView *noView;
    UIView *newverView;
    NSInteger _num;
    
    NSString *_signNum;
    NSString *_signTotal;
    NSString *_integralTotal;
    
    NSInteger m,n;
    
    UILabel *signNum,*signTotal,*integralTotal;
}
@property (strong, nonatomic) NSMutableArray *dataArr;

@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
@property (weak, nonatomic) IBOutlet UILabel *name;
@property (weak, nonatomic) IBOutlet UILabel *number;
@property (weak, nonatomic) IBOutlet UILabel *remainFloat;
@property (weak, nonatomic) IBOutlet UIButton *notiBtn;
@property (weak, nonatomic) IBOutlet UIButton *setBtn;

@property (strong, nonatomic) UIView *backView;
@property (strong, nonatomic) UIImageView *mainsignView;

@end

@implementation MeViewController

- (UIView *)backView
{
    
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
        _backView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
    }
    if (_backView.subviews.count==2) {
        
        [_backView insertSubview:self.mainsignView atIndex:0];
    }else{
        [_backView addSubview:self.mainsignView];
    }
    
    return _backView;
}
- (UIImageView *)mainsignView
{
    UIScrollView *scroll;
    UILabel *label;
    CGFloat width = 290;
    CGFloat height = 400;
    
    if (!_mainsignView) {
        
        
        _mainsignView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH/2-width/2, HEIGHT/2 - height/2, width, height)];
        _mainsignView.userInteractionEnabled = YES;
        _mainsignView.image = [UIImage imageNamed:@"广告2_meitu_1_meitu_2.jpg"];
        _mainsignView.layer.cornerRadius = 5;
        _mainsignView.clipsToBounds = YES;
        _mainsignView.backgroundColor = [UIColor whiteColor];
        
        signNum = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, width/3-10, 30)];
        signNum.text = [NSString stringWithFormat:@"连续签到:%@",_signNum];
        signNum.textColor = [UIColor whiteColor];
        [_mainsignView addSubview:signNum];
        font(signNum, 15);
        signTotal = [[UILabel alloc]initWithFrame:CGRectMake(width/3, 5, width/3-10, 30)];
        signTotal.text = [NSString stringWithFormat:@"签到总数:%@",_signTotal];
        font(signTotal, 15);
        signTotal.textColor = [UIColor whiteColor];
        [_mainsignView addSubview:signTotal];
        integralTotal = [[UILabel alloc]initWithFrame:CGRectMake(width * 2/3, 5, width/3-10, 30)];
        integralTotal.text = [NSString stringWithFormat:@"累计奖励:%@",_integralTotal];
        font(integralTotal, 15);
        integralTotal.textColor = [UIColor whiteColor];
        [_mainsignView addSubview:integralTotal];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setBackgroundImage:[UIImage imageNamed:@"write.png"] forState:UIControlStateNormal];
        button.frame = CGRectMake(width/2 - 30+5, 40, 60, 60);
        [button addTarget:self action:@selector(signClick) forControlEvents:UIControlEventTouchUpInside];
        [_mainsignView addSubview:button];
        
        scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(10, 105, width-20, height - 110)];
        scroll.tag = 777;
        scroll.showsVerticalScrollIndicator = NO;
        [_mainsignView addSubview:scroll];
        
        
        label = [[UILabel alloc]init];
        label.tag = 666;
        font(label, 14);
        label.textColor = [UIColor whiteColor];
        label.numberOfLines = 0;
        
        [scroll addSubview:label];
    }else{
        if ([_mainsignView viewWithTag:777]) {
            scroll = [_mainsignView viewWithTag:777];
        }
        if ([_mainsignView viewWithTag:666]) {
            label = [_mainsignView viewWithTag:666];
        }
    }
    NSString *content = [NSString stringWithFormat:@"签到规则\n\n1.每天只签到一次（按服务器系统时间为准）\n\n2.首次签到获得%ld积分奖励\n\n3.连续签到每天递增%ld积分奖励，例如：第一天%ld积分，第二天%ld积分\n\n4.连续签到%ld天及以上每天获得%ld积分奖励，例如：第%ld天%ld积分，第%ld天之后都是%ld积分，不再递增\n\n5.中断签到，则从头计算积分，例如：连续签到3天，第4天未签到，第5天签到获得%ld积分\n\n其他说明\n\n1.签到积分与应用下载获取的积分相同，可兑换海量商品，大家踊跃签到并下载应用\n\n2.最终解释权归本公司所有，对违规获取积分者保留追究责任权利",n,n,n,2*n,m,m*n,m,m*n,m,m*n,n];
    CGSize size = [content boundingRectWithSize:CGSizeMake(scroll.width, MAXFLOAT) options:(NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:label.font} context:nil].size;
    label.frame = CGRectMake(0, 0, scroll.width, size.height);
    
    label.text = content;
    [scroll setContentSize:CGSizeMake(width-20, label.frame.size.height)];
    return _mainsignView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _num = 0;
    [self initUI];
    [self showUserInfo:nil];
    _dataArr = [NSMutableArray array];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeUserinfo:) name:@"changeUserinfo" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeUserinfo:) name:@"leftNum" object:nil];
}

- (void)changeUserinfo:(NSNotification *)noti
{
    UIImage *ima = noti.object;
    [self showUserInfo:ima];
}

- (void)signClick
{
    NSLog(@"点击签到");
    [MyAFN POST:SIGNSAVE parameters:@{@"login_id":[Myuser sharedUser].login_id} block:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"status"]integerValue]) {
            if([[responseObject objectForKey:@"msg"] isEqualToString:@"交易成功!"]){
                if (_backView) {
                    [_backView Message:@"签到成功" HiddenAfterDelay:1];
                    _signNum = [responseObject objectForKey:@"signNum"]?[responseObject objectForKey:@"signNum"]:@"0";
                    _signTotal = [responseObject objectForKey:@"signTotal"]?[responseObject objectForKey:@"signTotal"]:@"0";
                    _integralTotal = [responseObject objectForKey:@"integralTotal"]?[responseObject objectForKey:@"integralTotal"]:@"0";
                    
                    if (signNum&&signTotal&&integralTotal) {
                        signNum.text = [NSString stringWithFormat:@"连续签到:%@",_signNum];
                        signTotal.text = [NSString stringWithFormat:@"签到总数:%@",_signTotal];
                        integralTotal.text = [NSString stringWithFormat:@"累计奖励:%@",_integralTotal];
                    }
                }
                NSString *num = [responseObject objectForKey:@"allTotalIntegral"];
                NSString *qstr = [NSString stringWithFormat:@"积分：%@ 分",num];
                NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
                [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, num.length)];
                
                self.number.attributedText = mstr;
                //self.number.text = [NSString stringWithFormat:@"积分：%@",[responseObject objectForKey:@"allTotalIntegral"]];
                [Myuser sharedUser].allTotalIntegral = [responseObject objectForKey:@"allTotalIntegral"];
            }else{
                if (_backView) {
                    [_backView Message:[responseObject objectForKey:@"msg"] HiddenAfterDelay:1];
                }
            }
        }
    
    } error:^(NSError *error) {
        
    } fromController:self];
}

- (void)checkNoti
{
    NSLog(@"%@",NSHomeDirectory());
    
    if (![Myuser sharedUser].login_id) {
        return;
    }
    
    NSDictionary *parameter;
    if ([[EGOCache globalCache]objectForKey:[Myuser sharedUser].login_id])
    {
        parameter = @{@"user_id":[Myuser sharedUser].login_id,@"flag":@(1)};
        
    }else{
        parameter = @{@"user_id":[Myuser sharedUser].login_id,@"flag":@(0)};
    }
    
    
    
    [MyAFN POST:SYSTEMNOTILIST parameters:parameter block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        [self.dataArr removeAllObjects];
        if ([[response objectForKey:@"status"]integerValue]) {
            
            NSMutableArray *array = [NSMutableArray array];
            if ([[EGOCache globalCache]objectForKey:[Myuser sharedUser].login_id])
            {
                NSDictionary *dic = (NSDictionary *)[[EGOCache globalCache]objectForKey:[Myuser sharedUser].login_id];
                
                _dataArr = [dic objectForKey:@"SystemNotification"];
                [array addObjectsFromArray:[response objectForKey:@"notViewedReplyList"]];
                
            }else{
                [array addObjectsFromArray:[response objectForKey:@"notViewedReplyList"]];
            }
            
            NSMutableArray *newArr = [NSMutableArray array];
            for (NSDictionary *dic in array) {
                
                SystemNotiModel *model = [[SystemNotiModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                
                [newArr addObject: model];
            }
            
            NSRange range = NSMakeRange(0, [newArr count]);
            
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            
            [self.dataArr insertObjects:newArr atIndexes:indexSet];
            
            for (SystemNotiModel *model in _dataArr) {
                if (!model.isViewed) {
                    [self giveNoti];
                    break;
                }
            }
        }
        
    }error:^(NSError *error) {
        
    }fromController:nil];
}

- (void)giveNoti
{
    noView.hidden = NO;
     _num = 1;
    
}

- (void)initUI
{
    _iconImage.layer.cornerRadius = 30*SCALEY;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toDetail)];
    
    [_iconImage addGestureRecognizer:tap];
    
    noView = [[UIView alloc]initWithFrame:CGRectMake(_notiBtn.frame.size.width*SCALEX-5, 0, 10, 10)];
    noView.backgroundColor = [UIColor redColor];
    noView.layer.cornerRadius = 5;
    
    [_notiBtn addSubview:noView];
    noView.hidden = YES;
    
//    if (NEWAPPVER) {
//        newverView = [[UIView alloc]initWithFrame:CGRectMake(_setBtn.frame.size.width*SCALEX, -5, 10, 10)];
//        newverView.backgroundColor = [UIColor redColor];
//        newverView.layer.cornerRadius = 5;
//        
//        [_setBtn addSubview:newverView];
//    }
    
}

- (void)toDetail
{
    if (USERID) {
        
        MeDetailViewController *detail = [[MeDetailViewController alloc]init];
        
        [self.navigationController pushViewController:detail animated:YES];
        
    }else{
        
        LoginViewController *login = [[LoginViewController alloc]init];
        [self.navigationController pushViewController:login animated:YES];
    }
}
- (IBAction)signIn:(id)sender {
    if (!USERID) {
        [self.view Message:@"请登录" HiddenAfterDelay:1];
        return;
    }
//    if(![self valiMobile:[Myuser sharedUser].login_id]){
//        [Myuser alertWithTitle:@"提示" Msg:@"还未绑定手机，前去绑定手机？" target:self action:^{
////            ForgetPasswordControllerViewController *fc = [[ForgetPasswordControllerViewController alloc]init];
////            
////            fc.isBinding = YES;
////            fc.uuid = USERID;
////            
////            [self.navigationController pushViewController:fc animated:YES];
//            
//            BindNumViewController *bind = [[BindNumViewController alloc]init];
//            bind.uuid = USERID;
//            
//            [self.navigationController pushViewController:bind animated:YES];
//        }];
//
//        return;
//    }
    
    [MyAFN POST:SIGNCHECK parameters:@{@"login_id":[Myuser sharedUser].login_id} block:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"status"]integerValue]) {
            if ([[responseObject objectForKey:@"is_expired"]integerValue]) {
                
                _signNum = [responseObject objectForKey:@"signNum"]?[responseObject objectForKey:@"signNum"]:@"0";
                _signTotal = [responseObject objectForKey:@"signTotal"]?[responseObject objectForKey:@"signTotal"]:@"0";
                _integralTotal = [responseObject objectForKey:@"integralTotal"]?[responseObject objectForKey:@"integralTotal"]:@"0";
                
                if (signNum&&signTotal&&integralTotal) {
                    signNum.text = [NSString stringWithFormat:@"连续签到:%@",_signNum];
                    signTotal.text = [NSString stringWithFormat:@"签到总数:%@",_signTotal];
                    integralTotal.text = [NSString stringWithFormat:@"累计奖励:%@",_integralTotal];
                }
                n = [[responseObject objectForKey:@"incrementItg"]integerValue];
                m = [[responseObject objectForKey:@"signCycle"]integerValue];
                [self.view addSubview:self.backView];
                
                
            }else{
                [self.view performSelector:@selector(Message:) withObject:@"签到已结束" afterDelay:0.5];
                
            }
        }else{
            [self.view performSelector:@selector(Message:) withObject:[responseObject objectForKey:@"msg"] afterDelay:0.5];
        }
    } error:^(NSError *error) {
        
    } fromController:self];
    
}

- (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}

- (void)showmsg:(NSString *)msg
{
    [self.view Message:msg HiddenAfterDelay:1];
}

- (IBAction)toSetting:(id)sender {
    
    SettingViewController *setting = [[SettingViewController alloc]init];
    setting.changeIcon = ^(UIImage *ima){
        
        self.iconImage.image = ima;
    };
    [self.navigationController pushViewController:setting animated:YES];
}
- (IBAction)myNumClick:(UIButton *)sender {
    
    if (!USERID) {
        [self.view Message:@"请登录" HiddenAfterDelay:1];
        return;
    }
//    [self.view Message:@"暂时未开通" HiddenAfterDelay:1];
    MyNumberViewController *myNum = [[MyNumberViewController alloc]init];
    myNum.title = @"酷吧积分";
    [self.navigationController pushViewController:myNum animated:YES];
}
- (IBAction)myWatchRecordClick:(id)sender {
//    if (!USERID) {
//        [self.view Message:@"请登录" HiddenAfterDelay:1];
//        return;
//    }
    VideoRecordController *record = [[VideoRecordController alloc]init];
    [self.navigationController pushViewController:record animated:YES];
}
- (IBAction)myDetailClick:(UIButton *)sender {
    
    if (!USERID) {
        [self.view Message:@"请登录" HiddenAfterDelay:1];
        return;
    }
    MeDetailViewController *detail = [[MeDetailViewController alloc]init];
    
    [self.navigationController pushViewController:detail animated:YES];
    
}


- (IBAction)exchangeWithNum:(id)sender {
    ProductShowController *controller = [[ProductShowController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}



- (IBAction)notiClick:(id)sender {
    
    if (!USERID) {
        [self.view Message:@"请登录" HiddenAfterDelay:1];
        return;
    }
    
    MyWalletController *wallet = [[MyWalletController alloc]init];
//    SystemNotificationController *sysno = [[SystemNotificationController alloc]init];
//    sysno.showM = ^(NSInteger num){
//        if (!num) {
//           noView.hidden = YES;
//            //self.navigationController.tabBarItem.badgeValue = nil;
//            [Myuser hideRedPoint:self];
//            _num = 0;
//            
//        }else{
//            _num = num;
//        }
//    };
//    sysno.title = @"消息";
//    sysno.dataArr = _dataArr;
    [self.navigationController pushViewController:wallet animated:YES];
}
- (IBAction)shareClick:(id)sender {
//    [self.view Message:@"暂时未开通" HiddenAfterDelay:1];
    RecommendViewController *recommend = [[RecommendViewController alloc]init];
    [self.navigationController pushViewController:recommend animated:YES];
}


- (void)showUserInfo:(UIImage *)ima
{
    Myuser *user = [Myuser sharedUser];
    
    if (user.icon) {
        [self.iconImage sd_setImageWithURL:[NSURL URLWithString:user.icon]placeholderImage:[UIImage imageNamed:@"icon3.png"]];
    }else{
        self.iconImage.image = [UIImage imageNamed:@"add"];
    }
    
    if (ima) {
        _iconImage.image = ima;
    }
    
    if (user.name) {
        self.name.text = user.name;
    }else{
        self.name.text = @"请登录";
        noView.hidden = YES;
    }
    
    if (user.allTotalIntegral) {
        
        NSString *qstr = [NSString stringWithFormat:@"积分：%@ 分",user.allTotalIntegral];
        NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
        [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, user.allTotalIntegral.length)];
        
        self.number.attributedText = mstr;
    }else{
        
        NSString *qstr = [NSString stringWithFormat:@"积分：%d 分",0];
        NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
        [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, 1)];
        
        self.number.attributedText = mstr;
    }
    //检测消息
//    if (USERID) {
//        [self checkNoti];
//    }
    
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *tou = [touches anyObject];
    
    if (_backView) {
        if (tou.view != _mainsignView) {
            
            [_backView removeFromSuperview];
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setNeedsStatusBarAppearanceUpdate];
    if ([ISBUS boolValue]) {
        
        if ([factory isEqualToString:@"TBS"]) {
           
            [MyCar getMAC:^{
                
                NSString *qstr = [NSString stringWithFormat:@"流量：%.2f M",[remainFlow floatValue]/1024/1024];
                NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc]initWithString:qstr];
                [mstr addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, qstr.length-5)];
                
                self.remainFloat.attributedText = mstr;
            }];
        }else{
            
            self.remainFloat.text = @"流量：未知";
        }
    }else{
        
        self.remainFloat.text = @"流量：未知";
    }
    
    //self.navigationController.tabBarItem.badgeValue = nil;
    [Myuser hideRedPoint:self];
    NSLog(@"%@",[Myuser sharedUser].icon);
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    if (_num) {
//        self.navigationController.tabBarItem.badgeValue = @"";
        [Myuser showRedPoint:self index:4];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
